<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\command;


use think\console\Input;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Db;

class AgentGetMoney extends BaseCommand
{
    protected function configure()
    {
        // 指令配置
        $this->setName('agent_get_money')
            ->setDescription('推广员获得推广费');
    }

    protected function execute(Input $input, Output $output){
        $this->setDb($input,$output);
    }

    protected function executeAction(Input $input, Output $output)
    {
        $config = Db::name('configuration')
            ->where('type','tradeSetting')
            ->select()
            ->toArray();
        $user = $ids = [];
        foreach ($config AS $index => $item){
            $agent_get_money_time = json_decode($item['configuration'],true)['agent_get_money_time'];
            $select = Db::name('agent_bill_temporary')
                ->field('id,user_id,amount,uniqid,order_id,order_no,commodity_id,order_commodity_id,sku_id,source_user_id,number,money')
                ->where('order_commodity_id','IN',function($sql) use ($agent_get_money_time,$item){
                    $sql->name('order_commodity')
                        ->field('id')
                        ->where('mall_id',$item['mall_id'])
                        ->where('update_time','<',date('Y-m-d H:i:s',time() - $agent_get_money_time * 86400))
                        ->where('delete_time IS NULL')
                        ->where('status',4);
                })
                ->where('mall_id',$item['mall_id'])
                ->where('status',0)
                ->select()
                ->toArray();
            $id = array_column($select,'id');
            $temp = [];
            foreach ($select AS $key => $value)
                $temp[$value['user_id']][] = $value['amount'];
            foreach ($temp AS $key => $value)
                $user[$key] = array_sum($value);
            $ids = array_merge($ids,$id);
        }
        try {
            Db::startTrans();
            foreach ($user AS $key => $value)
                Db::name('user_cash')
                    ->where('user_id', $key)
                    ->inc('agent_total', $value)
                    ->inc('agent', $value)
                    ->update(['update_time' => date('Y-m-d H:i:s')]);
            Db::name('agent_bill_temporary')
                ->where('id', 'IN', $ids)
                ->update(['status' => 1, 'update_time' => date('Y-m-d H:i:s')]);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            dd($e->getTraceAsString());
        }
        #考核佣金发放
//        $this->AssessmentGetMoney($config);

    }
    /**
     * * 考核自动发放佣金
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function AssessmentGetMoney($config)
    {
        $user = $ids = [];
        foreach ($config AS $index => $item) {
            $agent_get_money_time = json_decode($item['configuration'], true)['agent_get_money_time'];
            $select = Db::name('agent_bill_temporary')
                ->field('id,user_id,commission,amount,uniqid,order_id,order_no,commodity_id,order_commodity_id,sku_id,source_user_id,number,money')
                ->where('order_commodity_id', 'IN', function ($sql) use ($agent_get_money_time, $item) {
                    $sql->name('order_commodity')
                        ->field('id')
                        ->where('mall_id', $item['mall_id'])
                        ->where('update_time', '<', date('Y-m-d H:i:s', time() - $agent_get_money_time * 86400))
                        ->where('delete_time IS NULL')
                        ->where('status', 4);
                })
                ->where('mall_id', $item['mall_id'])
                ->where('assessment_status', 0)
                ->where('is_assessment', 1)
                ->select()
                ->toArray();
            $id = array_column($select, 'id');
            $temp = [];
            foreach ($select AS $key => $value)
                $temp[$value['user_id']][] = $value['commission'];
            foreach ($temp AS $key => $value)
                $user[$key] = array_sum($value);
            $ids = array_merge($ids, $id);
        }
        try {
            Db::startTrans();
            foreach ($user AS $key => $value)
                Db::name('user_cash')
                    ->where('user_id', $key)
                    ->inc('assessment_total', $value)
                    ->inc('assessment', $value)
                    ->update(['update_time' => date('Y-m-d H:i:s')]);
            Db::name('agent_bill_temporary')
                ->where('id', 'IN', $ids)
                ->update(['assessment_status' => 1, 'update_time' => date('Y-m-d H:i:s')]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            dd($e->getMessage());
        }
    }
}